const ws = require('nodejs-websocket');
const PORT = 3000
let count = 0;
const server = ws.createServer(connect => {
    console.log(connect);
    console.log('用户连接成功');
    count++
    connect.uerName = `用户${count}`
    // connect
    broadcast(`${connect.uerName}刘国强开着拖拉机加入群聊`)
      //用户传过来的数据
    connect.on('text',data => {
      console.log(`接受到的信息:${data}`);
      //返回接收到的数据
    //   connect.sendText(data);
    broadcast(data);
    })

    //关闭连接
    connect.on('close',data => {
       console.log('断开连接');
       count--;
       broadcast(`${connect.uerName}离开了群聊`)
    })
    //报错
    connect.on('error',() => {
        console.log('连接异常');
    })
})

const broadcast = (msg) => {
    server.connections.forEach(item => {
        //给每个用户发送
        item.send(msg)
    })
}
server.listen(PORT,() => {
    console.log('服务启动，端口号3000');
})